<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElNotification } from 'element-plus'
import moment from 'moment'
import { http } from '@/http'

// 文章列表数据
const articleData = ref<Article[] | any>([])
const currentPage = ref(1)
const pageSize = ref(5)
const totalItems = ref(0)

// 新增文章弹窗控制
const formVisible = ref(false)
const drawerVisible = ref(false)

// 章节列表（示例用，实际可从后端拉取）
const chapters = ref<string[]>([])

// 新增表单数据
const addForm = reactive({
  title: '',
  typeid: 0,
  chapter: '', // 章节字段
  createby: '',
  istop: 0,
  content: '', // markdown内容
  summary: '',
})

const feishuFrom = reactive({
  userAccessToken: '',
  documentId: '',
})

interface Article {
  id: number
  title: string
  summary: string
  filePath: string
  createBy: string | null
  isTop: boolean
  viewcount: number
  favoriteCount: number
  isDeleted: boolean
}

// // 格式化列表时间显示
// const formattedTableData = computed(() => {
//   return articleData.value.map((item) => ({
//     ...item,
//     createtime: formatTime(item.createtime),
//     updatetime: formatTime(item.updatetime),
//   }))
// })

// function formatTime(timeStamp: number) {
//   const seconds = timeStamp / 1000
//   const localTimeMoment = moment.unix(seconds).local()
//   return localTimeMoment.format('YYYY-MM-DD HH:mm:ss')
// }

// 请求文章列表
async function fetchData() {
  try {
    const response = await http.get(`/api/articles/list`, {
      // currentPage: currentPage.value,
      // pageSize: pageSize.value,
    })
    articleData.value = response.data
  } catch (error) {
    console.error('错误', error)
  }
}

// 新增文章
async function add() {
  try {
    // 提交新增文章数据，包括章节和markdown内容
    const response = await http.post('/api/articles/create', {
      ...addForm,
    })
    if (response.data.success === true) {
      resetForm()
      formVisible.value = false
      ElNotification({
        title: 'Success',
        message: '文章添加成功！',
        type: 'success',
        duration: 2000,
      })
      fetchData()
    } else {
      ElNotification({
        title: 'Error',
        message: '文章添加失败！文章名称已存在',
        type: 'error',
        duration: 2000,
      })
    }
  } catch (error) {
    console.error('错误', error)
  }
}

// 同步飞书文档示例调用（确保你有实现该方法）
const syncArticleFromFeishu = async () => {
  drawerVisible.value = !drawerVisible.value
  const userAccessToken = feishuFrom.userAccessToken
  const documentId = feishuFrom.documentId
  try {
    await http.post('/api/articles/syncFromFeishu', { documentId, userAccessToken })
    await fetchData() // 同步后刷新菜单
  } catch (error) {
    console.error(error)
  }
}

async function deleteArticle(id: number) {
  try {
    await http.post(`/api/articles/${id}/delete`) // 你需要后端实现此接口
    ElNotification.success('文章已移入回收站')
    fetchData() // 刷新列表
  } catch (error) {
    ElNotification.error('删除失败')
  }
}

// 重置表单
function resetForm() {
  addForm.title = ''
  addForm.typeid = 0
  addForm.chapter = ''
  addForm.createby = ''
  addForm.istop = 0
  addForm.content = ''
  addForm.summary = ''
  chapters.value = []
}

// 分页切换
function handleCurrentChange(val: number) {
  currentPage.value = val
  fetchData()
}

// 选类型时加载章节
function loadChapters(typeid: number) {
  if (typeid === 1) {
    chapters.value = ['第一章', '第二章']
  } else if (typeid === 2) {
    chapters.value = ['第一章']
  } else {
    chapters.value = []
  }
  addForm.chapter = ''
}

// 新增章节
function addChapter() {
  const newChapter = prompt('请输入新章节名')
  if (newChapter && !chapters.value.includes(newChapter)) {
    chapters.value.push(newChapter)
    addForm.chapter = newChapter
  }
}

// 上传文件前校验
function beforeUploadMd(file: File) {
  if (!file.name.endsWith('.md')) {
    ElNotification.error('请上传Markdown文件（.md）')
    return false
  }
  return true
}

// 自定义上传逻辑
async function uploadMdFile({ file, onSuccess, onError }: any) {
  const formData = new FormData()
  formData.append('file', file)
  try {
    const res = await http.post('/api/articles/uploadMd', formData) // 你后端实现接口
    onSuccess(res.data)
    addForm.content = res.data.content // 后端返回内容放这里
    ElNotification.success('Markdown 文件上传成功！')
  } catch (error) {
    ElNotification.error('上传失败')
    onError(error)
  }
}

onMounted(() => {
  fetchData()
})
</script>

<template>
  <el-divider />
  <div class="page-container">
    <div class="page-header">
      <div style="font-size: 1.2em; font-weight: bold">文章管理 - 新增文章</div>
      <div class="button-group">
        <el-button @click="formVisible = true" type="primary">添加文章</el-button>
        <el-upload
          :before-upload="beforeUploadMd"
          :http-request="uploadMdFile"
          :show-file-list="false"
          accept=".md"
        >
          <el-button type="primary">选择Markdown文件上传</el-button>
        </el-upload>
        <el-button @click="drawerVisible = !drawerVisible" type="primary">
          点击加载飞书文档
        </el-button>
      </div>
    </div>

    <!-- 文章列表 -->
    <div class="table-container">
      <el-table :data="articleData" stripe class="table-wrapper">
        <!-- 常规列：只放最常用的 3 列 -->
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="title" label="标题" min-width="180" show-overflow-tooltip />
        <el-table-column prop="summary" label="摘要" min-width="260" show-overflow-tooltip />
        <el-table-column prop="createBy" label="作者"></el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="deleteArticle(row.id)">删除</el-button>
          </template>
        </el-table-column>

        <!-- 展开行：一次性展示所有字段 -->
        <el-table-column type="expand" width="50">
          <template #default="{ row }">
            <el-card shadow="never" style="margin: 8px 48px 16px 48px">
              <el-descriptions :column="1">
                <el-descriptions-item label="文件路径">{{ row.filePath }}</el-descriptions-item>
                <el-descriptions-item label="顶置">
                  <el-tag :type="row.isTop ? 'danger' : ''">{{ row.isTop ? '是' : '否' }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="已删除">
                  <el-tag :type="row.isDeleted ? 'danger' : 'success'">
                    {{ row.isDeleted ? '是' : '否' }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="阅读量">{{ row.viewCount }}</el-descriptions-item>
                <el-descriptions-item label="收藏量">{{ row.favoriteCount }}</el-descriptions-item>
                <el-descriptions-item label="摘要">
                  <div style="white-space: pre-wrap; max-height: 160px; overflow: auto">
                    {{ row.summary }}
                  </div>
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        layout="prev, pager, next, jumper"
        :total="totalItems"
        class="pagination"
      />
      <el-divider />
    </div>

    <el-drawer v-model="drawerVisible" title="请输入参数" direction="rtl">
      <el-form
        label-position="right"
        label-width="auto"
        :model="feishuFrom"
        style="max-width: 600px"
      >
        <el-form-item label="userAccessToken">
          <el-input v-model="feishuFrom.userAccessToken" />
        </el-form-item>
        <el-form-item label="documentId">
          <el-input v-model="feishuFrom.documentId" />
        </el-form-item>
      </el-form>
      <el-button @click="syncArticleFromFeishu()"> 添加 </el-button>
    </el-drawer>
    <el-dialog
      v-model="formVisible"
      title="新增文章"
      width="90%"
      :before-close="() => (formVisible = false)"
      class="article-dialog"
    >
      <div class="dialog-content-wrapper">
        <!-- 左侧表单 -->
        <el-form label-width="80px" class="dialog-form">
          <el-form-item label="标题">
            <el-input v-model="addForm.title" autocomplete="off" />
          </el-form-item>

          <el-form-item label="类型">
            <el-select v-model="addForm.typeid" placeholder="请选择类型" @change="loadChapters">
              <el-option label="Java" :value="1" />
              <el-option label="Hadoop" :value="2" />
            </el-select>
          </el-form-item>

          <el-form-item label="章节">
            <el-select v-model="addForm.chapter" placeholder="请选择章节">
              <el-option
                v-for="chapter in chapters"
                :key="chapter"
                :label="chapter"
                :value="chapter"
              />
            </el-select>
            <el-button size="mini" @click="addChapter" style="margin-top: 5px">新增章节</el-button>
          </el-form-item>

          <el-form-item label="作者">
            <el-input v-model="addForm.createby" autocomplete="off" />
          </el-form-item>

          <el-form-item label="是否顶置">
            <el-select v-model="addForm.istop" placeholder="请选择">
              <el-option label="是" :value="1" />
              <el-option label="否" :value="0" />
            </el-select>
          </el-form-item>

          <el-form-item label="摘要">
            <el-input type="textarea" v-model="addForm.summary" autocomplete="off" rows="3" />
          </el-form-item>
        </el-form>

        <!-- 右侧markdown编辑器 -->
        <div class="dialog-editor">
          <v-md-editor
            v-model="addForm.content"
            height="100%"
            placeholder="在这里编写Markdown内容..."
            style="flex: 1; border: 1px solid #ddd; border-radius: 4px"
          />
        </div>
      </div>

      <template #footer>
        <el-button @click="resetForm">重置</el-button>
        <el-button @click="() => (formVisible = false)">取消</el-button>
        <el-button type="primary" @click="add">保存</el-button>
      </template>
    </el-dialog>

    <el-divider />
  </div>
</template>
<style scoped>
.button-group {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  gap: 20px;
}
.page-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap; /* 允许换行 */
  gap: 16px;
}
.page-title {
  font-size: 1.5rem;
  font-weight: 600;
  margin: 0;
  /* 确保标题本身不会过长导致问题 */
  word-break: break-all;
}
.action-buttons {
  display: flex;
  gap: 12px;
  flex-wrap: wrap; /* 允许按钮换行 */
}
.table-wrapper {
  width: 100%;
  overflow-x: auto;
  flex-grow: 1;
}

.pagination {
  padding: 20px 0 0;
  justify-content: flex-end;
}

/* --- 对话框样式 (保持不变) --- */
.dialog-content {
  display: flex;
  gap: 20px;
  height: calc(90vh - 120px);
}
.dialog-form {
  flex: 1;
  overflow-y: auto;
}
.dialog-editor {
  flex: 2;
  display: flex;
}
:deep(.v-md-editor) {
  width: 100%;
}

/* --- 终极响应式修复 --- */
@media (max-width: 480px) {
  /* 当屏幕宽度小于480px时 */
  .page-header {
    flex-direction: column; /* 1. 强制垂直堆叠 */
    align-items: flex-start; /* 2. 左对齐 */
  }
  .action-buttons {
    width: 100%; /* 3. 让按钮容器占满整行 */
  }
  .action-buttons > .el-button,
  .action-buttons > .el-upload {
    flex-grow: 1; /* 4. (可选) 让按钮平均填满宽度，更适合触摸 */
  }
}

/* --- 对话框移动端适配 (保持不变) --- */
@media (max-width: 768px) {
  .dialog-content {
    flex-direction: column;
    height: auto;
  }
  .dialog-editor {
    height: 400px;
    min-height: 400px;
  }
}
</style>
